package cn.ocars.playgame.pencilstudy.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import cn.ocars.playgame.pencilstudy.services.MiniCPMVRecognitionService
import cn.ocars.playgame.pencilstudy.ui.theme.PrimaryBlue

/**
 * MiniCPM-V 2.5模型演示界面
 * 展示使用MiniCPM-V 2.5多模态模型进行书写笔迹评分的功能
 */
@Composable
fun MultimodalGemmaDemo(
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var selectedCharacter by remember { mutableStateOf("大") }
    var selectedStrokeCount by remember { mutableStateOf(3) }
    var recognitionResult by remember { mutableStateOf<MiniCPMVRecognitionService.RecognitionResult?>(null) }
    var showApiDialog by remember { mutableStateOf(false) }
    
    // 字符数据
    val characterData = listOf(
        "一" to 1,
        "二" to 2,
        "三" to 3,
        "人" to 2,
        "大" to 3,
        "小" to 3,
        "中" to 4,
        "上" to 3,
        "下" to 3,
        "天" to 4
    )
    
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 标题栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "MiniCPM-V 2.5模型演示",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = PrimaryBlue
            )
            
            TextButton(onClick = onBackClick) {
                Text("返回")
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 字符选择器
        Text(
            text = "选择字符",
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            characterData.forEach { (char, strokes) ->
                FilterChip(
                    selected = selectedCharacter == char,
                    onClick = {
                        selectedCharacter = char
                        selectedStrokeCount = strokes
                        recognitionResult = null // 清除之前的识别结果
                    },
                    label = {
                        Text(char)
                    },
                    modifier = Modifier.weight(1f)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 书写区域
        Card(
            modifier = Modifier.fillMaxWidth(),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                        text = "请书写：$selectedCharacter ($selectedStrokeCount 笔画)",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                MultimodalGemmaWritingCard(
                    key = "$selectedCharacter-$selectedStrokeCount",
                    character = selectedCharacter,
                    expectedStrokeCount = selectedStrokeCount,
                    onWritingComplete = { result ->
                        recognitionResult = result
                    },
                    modifier = Modifier.size(150.dp)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 识别结果
        if (recognitionResult != null) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "MiniCPM-V 2.5模型识别结果",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = PrimaryBlue
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 总分
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text("总分：")
                        Text(
                            text = "${"%.1f".format(recognitionResult!!.totalScore * 100)}分",
                            fontSize = 20.sp,
                            fontWeight = FontWeight.Bold,
                            color = when {
                                recognitionResult!!.totalScore >= 0.9f -> PrimaryBlue
                                recognitionResult!!.totalScore >= 0.7f -> androidx.compose.ui.graphics.Color.Green
                                recognitionResult!!.totalScore >= 0.5f -> androidx.compose.ui.graphics.Color(0xFFFFA500) // 橙色
                                else -> androidx.compose.ui.graphics.Color.Red
                            }
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 识别详情
                    Text("目标字符：${recognitionResult!!.character}")
                    Text("置信度：${"%.2f".format(recognitionResult!!.confidence * 100)}%")
                    
                    // 笔画评分
                    if (recognitionResult!!.strokeScores.isNotEmpty()) {
                        Text("笔画评分：")
                        recognitionResult!!.strokeScores.forEachIndexed { index, score ->
                            Text("  笔画${index + 1}：${"%.2f".format(score * 100)}%")
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // AI反馈
                    Text(
                        text = "AI反馈：${recognitionResult!!.feedback}",
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
        }
        
        // API调用示例按钮
        Button(
            onClick = { showApiDialog = true },
            modifier = Modifier.fillMaxWidth(),
            colors = ButtonDefaults.buttonColors(containerColor = PrimaryBlue)
        ) {
            Text("查看API调用示例")
        }
    }
    
    // API调用示例对话框
    if (showApiDialog) {
        Dialog(onDismissRequest = { showApiDialog = false }) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "API调用示例",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = PrimaryBlue
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = """
                            // 创建MiniCPM-V 2.5模型书写卡片
                            MultimodalGemmaWritingCard(
                                character = "$selectedCharacter",
                                expectedStrokeCount = $selectedStrokeCount,
                                onWritingComplete = { result ->
                                    // 处理识别结果
                                    println("目标字符: ${'$'}{result.character}")
                                    println("总分: ${'$'}{result.totalScore * 100}")
                                    println("置信度: ${'$'}{result.confidence * 100}%")
                                    println("AI反馈: ${'$'}{result.feedback}")
                                }
                            )
                            
                            // MiniCPM-V 2.5识别结果包含:
                            // - character: 目标汉字
                            // - totalScore: 总分 (0-1)
                            // - confidence: 置信度 (0-1)
                            // - strokeScores: 每个笔画的评分列表 (0-1)
                            // - feedback: AI生成的反馈
                        """.trimIndent(),
                        style = MaterialTheme.typography.bodySmall
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Button(
                        onClick = { showApiDialog = false },
                        modifier = Modifier.align(Alignment.End)
                    ) {
                        Text("关闭")
                    }
                }
            }
        }
    }
}